#define TR_FILENAME  "brushwave_log.txt"

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <windows.h>

static FILE *fp;
static BOOL isActive = FALSE;

void OpenTrace();
void CloseTrace();

// ----------------------------------------------------------------------------
void EnableTrace(BOOL enable)
{
    isActive = enable;
}

// ----------------------------------------------------------------------------
void OpenTrace()
{
    if (!fp)
        fopen_s(&fp, TR_FILENAME, "a+" );
}

// ----------------------------------------------------------------------------
void CloseTrace()
{
    if (fp) { 
        fclose(fp); 
        fp = NULL; 
    }
}

// ----------------------------------------------------------------------------
void WriteTrace(const char* format, ...)
{
    if (isActive)
    {
        static char arg[256];
        SYSTEMTIME st;
       
        if (!fp) OpenTrace();
        
        GetLocalTime(&st);
        fprintf(fp, "\n[%04.4d-%02.2d-%02.2d - %02.2d:%02.2d:%02.2d.%03.3d] ",
            st.wYear, st.wMonth, st.wDay, 
            st.wHour, st.wMinute, st.wSecond, st.wMilliseconds );    

        if (format) {
            va_list ap;
            va_start(ap, format);
            vsprintf_s(arg, 256, format, ap);
            va_end(ap);
            fprintf(fp, "%s", arg);

            // write to debug output as well
            OutputDebugStr(arg);
            OutputDebugStr("\n");
        }    

        CloseTrace();
    }
}